export function ip_to_int(ip_str: String): number {
    let bytes: number[] = [];
    ip_str.split('.').forEach(byte => {
        bytes.push(parseInt(byte))
    })
    return new DataView(new Uint8Array(bytes).buffer).getUint32(0, false);
}

export function int_to_bytes(num: number | undefined): Uint8Array | undefined {
    if (num === undefined) return undefined;
    let buffer = new ArrayBuffer(4);
    let dataview = new DataView(buffer);
    dataview.setUint32(0, num, false);
    return new Uint8Array(buffer);
}

export function bytes_to_hex(bytes: Uint8Array): String {
    let hex: string[] = [];
    for (let i = 0; i < bytes.length; i++) {
        let byte = bytes[i].toString(16).toUpperCase();
        hex.push(byte.length < 2 ? '0' + byte : byte);
    }
    return hex.join(' ');
}

export function bytes_to_dec(bytes: Uint8Array): String {
    return bytes.join('.');
}

export function check_is_valid_ip_str(ip_str: string): boolean {
    if (! /^(\d{1,3}\.){3}\d{1,3}$/.test(ip_str)) {
        return false;
    }
    for (let byte of ip_str.split('.')) {
        if (parseInt(byte) > 255) {
            return false;
        }
    }
    return true;
}

export function is_valid_mac(mac_str: string): boolean {
    if (! /((\da-f){2}:){5}(\da-f){2}/i.test(mac_str))
        return false;
    mac_str.split(':').forEach(val => {
        if (parseInt(val) > 255)
            return false;
    })
    return true;
}
